package com.crazyhat.crazyhat.exception;

import java.util.List;

import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.crazyhat.crazyhat.pojo.Result;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {

        e.printStackTrace();

        if (StringUtils.hasLength(e.getMessage())) {
            return Result.error(e.getMessage());
        } else {
            return Result.error("操作错误");
        }
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationExceptions(MethodArgumentNotValidException e) {

        BindingResult result = e.getBindingResult();
        if (result==null) {
            return Result.error("输入的参数不合格");
        }
        List<FieldError> fieldErrors = result.getFieldErrors();

        if (fieldErrors==null) {
            return Result.error("输入的参数不合格");
        }

        StringBuilder errorMessage = new StringBuilder();
        for(FieldError error : fieldErrors){
            if (error!=null) {
                errorMessage
                .append(error.getField())
                .append(":")
                .append(error.getDefaultMessage())
                .append("<br>");
            }
        }

        return Result.error(errorMessage.toString());
    }
}
